home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / local / bin / lc.py < prev    next >
Encoding:
Python Source  |  2012-08-03  |  5.3 KB  |  138 lines

  1. #!/usr/bin/python
  2.  
  3. # The MIT License
  4. # Copyright (c) 2011 Christopher Pound
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. # THE SOFTWARE.
  20.  
  21. # lc.py -- language confluxer (http://www.ruf.rice.edu/~pound/lc.py)
  22. #
  23. # - Written by Christopher Pound (pound@rice.edu), July 1993.
  24. # - Loren Miller suggested I make sure lc starts by picking a
  25. #   letter pair that was at the beginning of a data word, Oct 95.
  26. # - Cleaned it up a little bit, March 95; more, September 01
  27. # - Python version, Jul 09
  28. #
  29. # The datafile should be a bunch of words from some language
  30. # with minimal punctuation or garbage (# starts a comment). 
  31.  
  32. from __future__ import with_statement
  33. from optparse import OptionParser
  34. import random
  35. import re
  36. import sys
  37.  
  38. class Pseudolanguage:
  39.  
  40.     def __init__(self, **dict):
  41.         """Set up a new pseudolanguage"""
  42.         dict.setdefault('name', '')
  43.         self.name = dict['name']
  44.         self.parsed = False
  45.         self.data = {}
  46.         self.inits = {}
  47.         self.pairs = {}
  48.  
  49.     def incorporate(self, files):
  50.         """Load list of files for this pseudolanguage into self.data"""
  51.         self.parsed = False
  52.         for f in files:
  53.             words = []
  54.             with open(f) as text:
  55.                 for line in text:
  56.                     line = line.strip()
  57.                     line = re.sub(r"#.*", "", line)
  58.                     words.extend(re.split(r"\s+", line))
  59.                 self.data[f] = words
  60.  
  61.     def delete(self, files):
  62.         """Delete a list of languages from self.data"""
  63.         self.parsed = False
  64.         for f in files:
  65.             del self.data[f]
  66.  
  67.     def parse(self):
  68.         """Parse pseudolanguage's data into self.inits and self.pairs"""
  69.         if not self.parsed:
  70.             self.inits.clear()
  71.             self.pairs.clear()
  72.             for f in self.data:
  73.                 for word in self.data[f]:
  74.                     word += ' '
  75.                     if len(word) > 3:
  76.                         if self.inits.has_key(word[0:2]):
  77.                             self.inits[word[0:2]].append(word[2:3])
  78.                         else:
  79.                             self.inits[word[0:2]] = [word[2:3]]
  80.                     pos = 0
  81.                     while pos < len(word)-2:
  82.                         if self.pairs.has_key(word[pos:pos+2]):
  83.                             self.pairs[word[pos:pos+2]].append(word[pos+2])
  84.                         else:
  85.                             self.pairs[word[pos:pos+2]] = [word[pos+2]]
  86.                         pos = pos + 1
  87.             self.parsed = True
  88.  
  89.     def dump(self):
  90.         """Print the current parsed data; use pickle for inflatable dumps"""
  91.         self.parse()
  92.         print 'name = """', self.name, '"""'
  93.         print "dump = { 'inits': ", self.inits, ","
  94.         print "'pairs': ", self.pairs, " }"
  95.  
  96.     def generate(self, number, min, max):
  97.         """Generate list of words of min and max lengths"""
  98.         self.parse()
  99.         wordlist = []
  100.         while len(wordlist) < number:
  101.             word = random.choice(self.inits.keys())
  102.             while word.find(' ') == -1:
  103.                 word += random.choice(self.pairs[word[-2:]])
  104.             word = word.strip()
  105.             if len(word) >= min and len(word) <= max:
  106.                 wordlist.append(word)
  107.         return wordlist
  108.  
  109. if __name__ == '__main__':
  110.  
  111.     usage = "usage: %prog [options] datafile1 [datafile2 ...]"
  112.     parser = OptionParser(usage=usage, version="%prog 1.0")
  113.     parser.add_option("-d", "--dump", action="store_true", 
  114.                      dest="dump", default=False,
  115.                      help="Dump internal representation of the pseudolanguage")
  116.     parser.add_option("-g", "--generate", type="int", dest="num",
  117.                      help="Generate specified number of words")
  118.     parser.add_option("--min", type="int", dest="min", default=3,
  119.                      help="Set the minimum length of each word")
  120.     parser.add_option("--max", type="int", dest="max", default=9,
  121.                      help="Set the maximum length of each word")
  122.     parser.add_option("--name", dest="name", default=' ',
  123.                      help="Set the name of the pseudolanguage")
  124.     (options, args) = parser.parse_args()
  125.  
  126.     aLanguage = Pseudolanguage(name=options.name)
  127.     aLanguage.incorporate(args)
  128.     if options.dump:
  129.         aLanguage.dump()
  130.     else:
  131.         results = aLanguage.generate(options.num, options.min, options.max)
  132.         for word in results:
  133.             print word
  134.